package com.googlecode.futurecode.xproject.user;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.googlecode.futurecode.xproject.types.message.user.getusers.GetUsersRequest;
import com.googlecode.futurecode.xproject.types.message.user.getusers.GetUsersResponse;
import com.googlecode.futurecode.xproject.types.message.user.login.LoginRequest;
import com.googlecode.futurecode.xproject.types.message.user.login.LoginResponse;
import com.googlecode.futurecode.xproject.util.XProjectConstants;
import com.googlecode.futurecode.xproject.util.encode.XProjectMd5PasswordEncoder;

public class ImplUserService extends SqlSessionDaoSupport implements UserPortType {

	public GetUsersResponse getUsers(GetUsersRequest request) throws GetUsersFault {
		GetUsersResponse response = new GetUsersResponse();
		try {
			int pageNumber = request.getPageNumber();
			int pageSize = request.getPageSize();
			RowBounds rowBounds = new RowBounds((pageNumber-1)*pageSize, pageSize);
			List users = (List) getSqlSession().selectList(
					"com.googlecode.futurecode.xproject.mapper.UserMapper.getUser", null, rowBounds);
			response.getUsers().addAll(users);

			int userCount = (Integer) getSqlSession().selectOne(
					"com.googlecode.futurecode.xproject.mapper.UserMapper.getRecordCount", "xp_user");
			response.setTotalCount(userCount);
		} catch (Exception e) {
			throw new GetUsersFault(e.getMessage());
		}
		return response;
	}

	public LoginResponse login(LoginRequest request) throws LoginFault {
		LoginResponse response = new LoginResponse();
		String loginName = request.getLoginName();
		XProjectMd5PasswordEncoder passwordEncoder = new XProjectMd5PasswordEncoder();
		String encodePassword = passwordEncoder.encodePassword(request.getPassword(), XProjectConstants.ENCODE_SALT);
		
		/*Map param = new HashMap();
		param.put("loginName", loginName);
		param.put("password", encodePassword);*/
		System.out.println("loginName:" + loginName);
		System.out.println("password:" + encodePassword);
		XpUser param = new XpUser();
		param.setLoginName(loginName);
		param.setPassword(encodePassword);
		try {
			XpUser user = (XpUser) getSqlSession().selectOne(
					"com.googlecode.futurecode.xproject.mapper.UserMapper.login", param);
			response.setUser(user);
		} catch (Exception e) {
			throw new LoginFault(XProjectConstants.USER_OR_PWD_ERROR);
		}
		return response;
	}

}
